<template>
  <view class="address-list">
    <view v-if="addresses.length === 0" class="empty">
      <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">暂无收货地址</text>
    </view>
    <view v-else>
      <address-item
        v-for="item in addresses"
        :key="item.id"
        :address="item"
        @select="selectAddress"
        @edit="editAddress"
        @delete="deleteAddress"
        @setDefault="setDefault"
      />
    </view>
    <button class="add-btn" @click="addAddress">+ 新增收货地址</button>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onShow,onLoad } from '@dcloudio/uni-app';
import { addressApi } from '@/api/address.js';
import AddressItem from '@/components/address-item.vue';
import common from '@/utils/common.js';

const addresses = ref([]);
const isSelectMode = ref(false);

// 页面加载时获取参数
onLoad((options) => {
  isSelectMode.value = options.select === 'true';
  console.log('地址选择模式:', isSelectMode.value);
});

const loadAddresses = async () => {
  try {
  const res = await addressApi.getAddresses();
  addresses.value = res.data || [];
    console.log('地址列表:', addresses.value);
  } catch (error) {
    console.error('获取地址列表失败:', error);
    uni.showToast({
      title: '获取地址列表失败',
      icon: 'none'
    });
  }
};

const addAddress = () => {
  uni.navigateTo({ url: '/pages/address/edit' });
};

const editAddress = (id) => {
  uni.navigateTo({ url: `/pages/address/edit?id=${id}` });
};

const deleteAddress = async (id) => {
  const confirm = await new Promise(resolve => {
    uni.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success: res => resolve(res.confirm)
    });
  });
  if (confirm) {
    try {
    await addressApi.deleteAddress(id);
    uni.showToast({ title: '删除成功', icon: 'success' });
    loadAddresses();
    } catch (error) {
      console.error('删除地址失败:', error);
      uni.showToast({
        title: '删除失败，请重试',
        icon: 'none'
      });
    }
  }
};

const setDefault = async (id) => {
  try {
  await addressApi.setDefaultAddress(id);
  uni.showToast({ title: '设置成功', icon: 'success' });
  loadAddresses();
  } catch (error) {
    console.error('设置默认地址失败:', error);
    uni.showToast({
      title: '设置失败，请重试',
      icon: 'none'
    });
  }
};

const selectAddress = (address) => {
  // 检查是否是选择模式
  if (isSelectMode.value) {
    // 获取页面实例
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    
    // 准备返回的地址数据
    const selectedAddress = {
      ...address,
      // 确保字段名称一致
      recipientName: address.recipientName || address.recipient,
      recipientPhone: address.recipientPhone || address.phone,
      detailAddress: address.detailAddress || address.detail
    };
    
    console.log('选择的地址:', selectedAddress);
    
    // 使用页面实例的事件通道返回数据
    if (currentPage.$page && currentPage.$page.getOpenerEventChannel) {
      const eventChannel = currentPage.$page.getOpenerEventChannel();
      if (eventChannel && eventChannel.emit) {
        eventChannel.emit('addressSelected', selectedAddress);
      }
    } else {
      // 备用方案：使用全局事件
      uni.$emit('addressSelected', selectedAddress);
    }
    
    // 返回上一页
    uni.navigateBack();
  }
};

onShow(() => {
  loadAddresses();
});
</script>

<style scoped>
.address-list {
  min-height: 100vh;
  padding: 30rpx;
  background-color: #f7f7f7;
  position: relative;
  padding-bottom: 150rpx;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
}

.add-btn {
  position: fixed;
  bottom: 40rpx;
  left: 30rpx;
  right: 30rpx;
  height: 100rpx;
  background-color: #ffcc00;
  color: #333;
  font-size: 34rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 204, 0, 0.3);
}
</style> 